package com.distribution.system.utils.http;

import com.distribution.common.exception.base.BaseException;
import com.distribution.common.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;

/**
 * @author DESTINY-HLP
 */
@Slf4j
public class HttpRequestUtils {
    /**
     * 向指定URL发送GET方法的请求
     *
     * @param url   发送请求的URL
     * @param param 请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
     * @return URL 所代表远程资源的响应结果
     */
    public static String sendGet(String url, String param) {
        return sendGetWithHeader(url, null, param);
    }
    public static String sendGetWithHeader(String url, Map<String,String> headerMap, String param) {
        log.info("GET请求入参:{},URL={}", param, url);
        StringBuilder result = new StringBuilder();
        BufferedReader in = null;
        try {
            String urlNameString = StringUtils.isEmpty(param) ? url : url + "?" + param;
            URL realUrl = new URL(urlNameString);
            // 打开和URL之间的连接
            URLConnection connection = realUrl.openConnection();
            // 设置通用的请求属性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 设置传递的请求头
            if (headerMap != null) {
                headerMap.forEach(connection::setRequestProperty);
            }
            // 建立实际的连接
            connection.connect();
            // 获取所有响应头字段
            Map<String, List<String>> map = connection.getHeaderFields();
            // 遍历所有的响应头字段
            for (String key : map.keySet()) {
                System.out.println(key + "--->" + map.get(key));
            }
            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result.append(line);
            }
        } catch (Exception e) {
            log.error("发送GET请求出现异常！", e);
        }
        // 使用finally块来关闭输入流
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                log.error("发送GET请求出现异常！", e2);
            }
        }
        log.info("GET请求结果:{}", result);
        return result.toString();
    }

    /**
     * 向指定URL 发送 post请求
     *
     * @param urlPath 请求路径
     * @param param 携带的json数据
     * @return 结果状态
     */
    public static String sendPost(String urlPath, String param) {
        return sendPostWithHeader(urlPath, null, param);
    }
    public static String sendPostWithHeader(String urlPath, Map<String,String> headerMap, String param) {
        log.info("POST请求入参:{},URL={}", param, urlPath);
        // HttpClient 6.0被抛弃了
        String result = "";
        BufferedReader reader = null;
        URL url = null;
        HttpURLConnection conn = null;
        try {
            url = new URL(urlPath);
            conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            conn.setRequestProperty("Connection", "Keep-Alive");
            conn.setRequestProperty("Charset", "UTF-8");
            // 设置文件类型:
            conn.setRequestProperty("Content-Type", "application/json");
            // 设置接收类型否则返回415错误
//            conn.setRequestProperty("Accept","*/*");//此处为暴力方法设置接受所有类型，以此来防范返回415
            conn.setRequestProperty("Accept", "application/json");
            // 设置传递的请求头
            if (headerMap != null) {
                headerMap.forEach(conn::setRequestProperty);
            }
            // 往服务器里面发送数据
            byte[] dataLength = param.getBytes();
            // 设置文件长度
            conn.setRequestProperty("Content-Length", String.valueOf(dataLength.length));
            OutputStream outputStream = conn.getOutputStream();
            outputStream.write(param.getBytes(StandardCharsets.UTF_8));
            outputStream.flush();
            outputStream.close();
        } catch (Exception e) {
            log.error("创建第三方请求失败：" + e.getMessage());
            throw new BaseException("创建第三方请求失败");
        }
        try {
            if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
                reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8));
                result = reader.readLine();
            }
        } catch (Exception e) {
            log.error("发送POST请求出现异常！", e);
            throw new BaseException("向三方发起请求时，发生异常。");
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    log.error("发送POST请求出现异常！", e);
                }
            }
        }
        try {
            if (conn.getResponseCode() == HttpURLConnection.HTTP_INTERNAL_ERROR) {
                throw new RuntimeException("请求三方接口报错: 状态码为500");
            }
        } catch (IOException e) {
            throw new BaseException("向三方发起请求时获取响应失败");
        }
        log.info("POST请求结果:{}", result);
        return result;
    }
}
